package com.ruoyi.system.xmlAbstract.interfaces.templateFactory;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.system.xmlAbstract.XmlGenerateAbstract;
import com.ruoyi.system.xmlAbstract.interfaces.templateInterfaces.XmlTemplateInterface;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author : anxinr
 * @date : 2023/1/17 11:02
 */
@Slf4j
@Component
public class TemplateFactory {
    private static Map<String, XmlTemplateInterface> map = new HashMap<>() ;
    @Autowired
    private ApplicationContext applicationContext ;

    public TemplateFactory() throws InterruptedException {
        /**
         * 避免因为spring容器因为加载顺序出现数据没有初始化的情况
         * 使用异步线程，不影响程序正常启动
         * */
        new Thread(()->{
            while (CollectionUtil.isEmpty(map)){
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (ObjectUtil.isNotEmpty(applicationContext)){
                    map = applicationContext.getBeansOfType(XmlTemplateInterface.class);
                }
                if (ObjectUtil.isNotEmpty(map)){
                    log.info("模板初始化成功!");
                }
            }
        }).start();
    }

    public static XmlGenerateAbstract getInstance(String code) throws Exception {
        XmlTemplateInterface xmlTemplateInterface = map.get(code);
        if (ObjectUtil.isEmpty(xmlTemplateInterface)){
            throw new Exception("没有该模板存在!") ;
        }
        return xmlTemplateInterface.generateXmlTemplate() ;
    }
}
